package com.wbao.dianniu.db;

import java.io.File;
import java.io.IOException;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;

import com.wbao.dianniu.R;
import com.wbao.dianniu.data.AccountInfo;
import com.wbao.dianniu.data.LoginResponse;

public class DbManager {

	private String CREATE_TAB = "CREATE TABLE IF NOT EXISTS tbl_province( id  integer primary key, " +
			"name varchar," +
			 " alias varchar ) ";
	private String DATABASE_PARTH = Environment.getExternalStorageDirectory().getPath() + "/dianniu.db";
	public SQLiteDatabase db = null;
	private int path = R.raw.dianniu;
	private Context mContext;
	private final String USER_TAB = "user";
	private final String CONFIG_TAB = "config";
	public static String url = "";
	
	public DbManager(Context context) {
		// TODO Auto-generated constructor stub
		mContext = context;
	}
	
	public void initDataBase(){
		File dir = new File(DATABASE_PARTH); // 判断数据库是否存在
		if (db != null && db.isOpen()){
			db.close();
			db = null;
		}
		if (!dir.exists()) { // 数据库不存在 则创建
			//System.out.println("数据库不存在");
			try {
				// 拷贝数据库 返回0为成功，返回-1为拷贝失败
				dir.createNewFile();
				DatabaseTools dt = new DatabaseTools();
				dt.copyDatabase(mContext, DATABASE_PARTH, path);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			//System.out.println("数据库已存在");
		}
		url = getUrl();
		
	}
	
	  //登录成功 保存token
	  public  int saveToken(UserInfo user){
		  openDatabase();
		  if(db.isOpen()){
			  ContentValues values = new ContentValues();
		       values.put(UserInfo. MOBILE, user.getMobile());
		       values.put(UserInfo. TOKEN, user.getToken());
		       values.put(UserInfo. USERNAME, user.getUserName());
		       values.put(UserInfo. PASSWORD, user.getPassword());
		       int uid = db.update(USER_TAB, values, "mobile=?", new String[]{ user.getMobile()});
		       Log. e("SaveUserInfo", uid + "");
		       return uid;
		  }else{
			 // System.out.println("数据库已存在");
			  return -1;
		  }
	  }
	  
	  //更新配置信息
	  public long updateConfig(String mobile,LoginResponse resp){
		  long uid = -1;
		  if(null == resp){
			  return uid;
		  }
		  openDatabase();
		  if(db.isOpen()){
			  ContentValues values = new ContentValues();
			  values.put(UserInfo.MOBILE, mobile);
		       values.put(AccountInfo. ACCOUNTID, resp.getAccountInfo().getId());
		       values.put(AccountInfo. HEADPC, resp.getAccountInfo().getHeadPic());
		       values.put(AccountInfo. REALNAME, resp.getAccountInfo().getRealName());
		       values.put(AccountInfo. CREATEDATE, resp.getAccountInfo().getCreateDate());
		       
//		       values.put(Config. CDNACCESSKEY, resp.getConfig().getCdnAccessKey());
//		       values.put(Config. CDNACCESSKEYSECRET, resp.getConfig().getCdnAccessKeySecret());
//		       values.put(Config. CDNBACKETNAME, resp.getConfig().getCdnBacketName());
//		       values.put(Config. CDNDOWNURL, resp.getConfig().getCdnDownUrl());
//		       values.put(Config. CDNUPURL, resp.getConfig().getCdnUpUrl());
			  //不存在该条记录，则插入，存在就更新
			  if(isExistMobile(mobile)){
				  // 更新记录
				  uid = db.update(USER_TAB, values, "mobile=?", new String[]{mobile});
			  }else{
				  uid = db.insert(USER_TAB, UserInfo.ID, values);
			  }
			  Log. e("SaveUserInfo", uid + "");
			  closeDatabase();
			  return uid;
		  }else{
			 // System.out.println("数据库已关闭");
			  return -1l;
		  }
		  
	  }
	  
	  public boolean isExistMobile(String mobile){
		  boolean ret = false;
		  openDatabase();
		  if(db.isOpen()){
			  String sql = "select mobile from " + USER_TAB + " where "+UserInfo.MOBILE +"=" + mobile;
			  //System.out.println(sql);
			  Cursor cursor = db.rawQuery(sql, null);
			  while (null != cursor && cursor.moveToNext()) {
				 String mb =  cursor.getString(0);
				 if(!mb.isEmpty()){
					 ret = true;
				 }
			  }
		  }
		  return ret;
	  }
	  
	  
	// 删除users表的记录
	  public int DelUserInfo(String UserId) {
		  openDatabase();
		  if(db.isOpen()){
			  int id = db.delete(USER_TAB,
					  UserInfo. MOBILE + "=?", new String[]{UserId});
			  Log. e("DelUserInfo", id + "");
			  closeDatabase();
			  return 0;
		  }else{
			 // System.out.println("database open fail");
			  return -1;
		  }
	  }
	  
	/**
	 * 拿到token
	 * @param mobile
	 * @return
	 */
	public String getToken(String mobile) {
		String sql = "select token from " + USER_TAB + " where "
				+ UserInfo.MOBILE + " = " + mobile;
		String token = "";
		openDatabase();
		if (db.isOpen()) {
			Cursor cursor = db.rawQuery(sql, null);
			while (null != cursor && cursor.moveToNext()) {
				token = cursor.getString(0);
			}
			closeDatabase();
		} else {
			//System.out.println("database open fail");
		}

		return token;
	}
	
	/**
	 * 获取url
	 * @return
	 */
	public String getUrl(){
		String sql = "select url  from " + CONFIG_TAB;
		String url = "";
		openDatabase();
		if(db.isOpen()){
			Cursor cursor = db.rawQuery(sql , null);
			while(null!=cursor&&cursor.moveToNext()){
				url = cursor.getString(0);
			}
			System.out.println("url=" + url);
			closeDatabase();
		}else{
			 System.out.println("database open fail");
		 }
		return url;
	}
	
	public String getAccountId(String mobile){
		String sql = "select "+AccountInfo.ACCOUNTID+" from " + USER_TAB + " where "
				+ UserInfo.MOBILE + " = " + mobile;
		String accountId = "";
		openDatabase();
		if (db.isOpen()) {
			Cursor cursor = db.rawQuery(sql, null);
			while (null != cursor && cursor.moveToNext()) {
				accountId = cursor.getString(0);
			}
			closeDatabase();
		} else {
			//System.out.println("database open fail");
		}
		return accountId;
	}
	
	/**
	 * 关闭数据库
	 */
	private void closeDatabase() {
		if (null != db)
			db.close();
			db = null;
	}
	
	private void openDatabase() {
		if (db == null) {
			db = SQLiteDatabase.openDatabase(DATABASE_PARTH, null,
					SQLiteDatabase.OPEN_READWRITE);
		}
	}
	public void creatTab(){
		openDatabase();
		if(null != db){
			db.execSQL(CREATE_TAB);
		}
	}
}
